package struts.util;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;

public class StrutsConfig {
	
	public StrutsConfig(){
		
	}
	
	public static Map<String, XmlBean> parseXml(String xmlPath)throws Exception {
		
		SAXBuilder builder = new SAXBuilder();
		Document document = builder.build(new File(xmlPath));
		Element root = document.getRootElement();
//		Element formBeans = root.getChild("formbeans");
//	    List<Element> forms = formBeans.getChildren();
//	    for (Element element : forms) {
//	    	String name = element.getAttributeValue("name");
//	    	String clas = element.getAttributeValue("class");
//	    	
//	    }
	    Map<String, XmlBean> rMap = new HashMap<String,XmlBean>();
	    Element actionMapping = root.getChild("action-mapping");
	    List<Element> actions = actionMapping.getChildren();
	    
	    for (Element element : actions) {
	    	XmlBean xmlBean = new XmlBean();
	    	String name = element.getAttributeValue("name");
	    	xmlBean.setBeanName(name);
	    	Element formBeans = root.getChild("formbeans");
	    	List<Element> forms = formBeans.getChildren();
	    	for (Element form : forms) {
	    		if (name.equals(form.getAttributeValue("name"))) {
	    			String formClass = form.getAttributeValue("class");
	    			xmlBean.setFormClass(formClass);
	    			break;
	    		}
	    	}
	    	String path = element.getAttributeValue("path");
	    	xmlBean.setPath(path);
	    	xmlBean.setActionClass(element.getAttributeValue("class"));
	    	
	    	List<Element> forwards = element.getChildren();
	    	Map<String, String> map = new HashMap<String,String>();
	    	for (Element forward : forwards) {
	    		String fname = forward.getAttributeValue("name");
	    		String fvalue = forward.getAttributeValue("value");
	    		map.put(fname, fvalue);
	    	}
	    	xmlBean.setActionForward(map);
	    	rMap.put(path, xmlBean);
	    }
	    
	    return rMap;
	}

}
